package com.sponge.dao.imp;

import com.sponge.bean.entity.CreditEntity;
import com.sponge.bean.enumerate.EntityCategory;
import com.sponge.bean.enumerate.EntitySecondaryCategory;
import com.sponge.bean.enumerate.EntityStatus;
import com.sponge.bean.enumerate.EntityThirdCategory;
import com.sponge.constant.ErrorMessage;
import com.sponge.constant.GlobalConstant;
import com.sponge.utils.LogUtil;
import com.sponge.utils.MathUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class CreditEntityDaoImpl extends BaseDaoImpl<CreditEntity> {

    @Autowired
    private MathUtils mathUtils;

    public boolean insertCreditEntity(String entityIdentityNumber,String entityName, String password){
        String insertCreditEntity = "insert into credit_entity(entity_id,entity_category,entity_identity_number,entity_name,password,secondary_category,third_category,entity_status,credit_value,add_time,update_time) values(?,?,?,?,?,?,?,?,?,?,?);";
        int gender = EntitySecondaryCategory.UNKNOW.ordinal();
        int i = Integer.parseInt(entityIdentityNumber.substring(16, 17));
        if (i % 2 == 0) {
            gender = EntitySecondaryCategory.FEMALE.ordinal();
        } else {
            gender = EntitySecondaryCategory.MALE.ordinal();
        }
        boolean addSuccess = false;
        int insertCount = 0;
//        String defaultPassword = entityIdentityNumber.substring(8, 14);
        long entityId = 0L;
        while (!addSuccess && insertCount < 5) {
            long addTime = System.currentTimeMillis();
            entityId = mathUtils.getFixedLengthNumberByChar(GlobalConstant.USER_ID_LENGTH);
            Object[] parameters = {entityId, EntityCategory.CREDIT_USER.ordinal(), entityIdentityNumber,entityName,password,gender, EntityThirdCategory.UNSORTED.ordinal(), EntityStatus.ADDED.ordinal(),0,addTime, addTime};
            addSuccess = update(insertCreditEntity, parameters);
            insertCount++;
        }
        if (addSuccess){
            CreditEntity creditEntity = queryCreditEntityByID(entityId);
            LogUtil.info(CreditEntityDaoImpl.class,creditEntity.toString());
        }else{
            LogUtil.error(CreditEntityDaoImpl.class, ErrorMessage.sql_exception);
        }
        return addSuccess;
    }

    public CreditEntity queryCreditEntityByID(long userId){
        CreditEntity creditEntity = null;
        String sql = "SELECT * FROM CREDIT_ENTITY WHERE ENTITY_ID = ?;";
        Object[] parameters = {userId};
        creditEntity = query(sql, parameters);
        return creditEntity;
    }
}
